package cn.geminis.auth.server.service.loginHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author puddi
 */
@AllArgsConstructor
@Slf4j
@Service
public class JsonFailureHandler implements AuthenticationFailureHandler {

    private final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());

        var result = new HashMap<String, Object>(8);
        result.put("message", e.getMessage());
        response.setContentType("application/json;charset=utf-8");
        var out = response.getWriter();
        out.write(objectMapper.writeValueAsString(result));
        out.flush();

//        MDC.put("username", e);
        log.info("认证失败");

    }
}
